<template>
  <div class="realtimemonito-box">
    <!-- 下拉列表 -->
    <el-card class="content__left">
      <realtimemonito-menu :data="menus" v-model:menu-id="menuId" v-model:open-id="openId" @menu-click="commEvent.menuClick" />
    </el-card>
    <!-- 展示信息 -->
    <div class="content__right">
      <el-card>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="header-search">
              <div class="header-search__item">
                <div class="item__label">生产设备：</div>
                <div class="item__value">
                  <el-select v-model="searchValue.deviceId" filterable>
                    <el-option v-for="item in devices" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <el-row justify="end">
              <el-button type="primary" icon="Search" @click="commEvent.getRealTimeData"> 搜索 </el-button>
              <el-button icon="Refresh" @click="commEvent.onReset">重置</el-button>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row justify="end">
              <el-button type="success" icon="Download" @click="showExportDialog = true"> 导出停机数据 </el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="mt10">
        <div class="card__title">三相电流统计</div>
        <div class="chart-container">
          <ECharts :option="chartOption" :height="400" />
        </div>
      </el-card>
    </div>

    <!-- 导出停机数据弹窗 -->
    <ExportDowntimeDialog v-model="showExportDialog" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from "vue"
import RealtimemonitoMenu, { MenuType } from "./components/RealtimemonitoMenu.vue"
import ExportDowntimeDialog from "./components/ExportDowntimeDialog.vue"
import ECharts from "@/components/ECharts/index.vue"
import { organTree } from "@/api/modules/system"
import { SystemSpace as SystemApi } from "@/api/interface/system"
import { deviceList } from "@/api/modules/archive"
import { SystemSpace as SystemArchive } from "@/api/interface/archive"
import { RealTimeStatQuery } from "@/api/modules/energy"

// 参数
// 搜索值
const searchValue = ref({
  deviceId: undefined as number | undefined
})
// 菜单值
const menuValue = ref({
  factoryId: undefined as undefined | number,
  lineId: undefined as undefined | number
})
const showExportDialog = ref<boolean>(false) // 显示导出弹窗
const openId = ref<number[]>([]) // 菜单展开id
const menuId = ref<number>(-1) // 菜单选中id
const menus = ref<MenuType[]>([]) // 菜单树结构
const devices = ref<SystemArchive.DeviceList[]>([]) // 设备信息
const currentData = ref<
  Array<{
    valueA: number
    valueB: number
    valueC: number
    dataTime: string
  }>
>([]) // 三相电流数据

// 图表配置
const chartOption = computed(() => {
  // 动态计算电流最大值
  const maxValue = computed(() => {
    if (!currentData.value.length) return 150 // 默认值

    // 获取所有电流值的最大值
    const allValues = currentData.value.flatMap(item => [item.valueA, item.valueB, item.valueC])
    const dataMax = Math.max(...allValues)

    // 在最大值基础上增加20%余量，确保图表显示效果
    return Math.ceil(dataMax * 1.2)
  })

  return {
    title: {
      text: "三相电流统计",
      left: "center"
    },
    tooltip: {
      trigger: "axis" as const,
      axisPointer: {
        type: "cross" as const
      }
    },
    legend: {
      data: ["A相电流", "B相电流", "C相电流"],
      top: 30
    },
    grid: {
      top: 80,
      left: 50,
      right: 50,
      bottom: 50
    },
    xAxis: {
      type: "category" as const,
      data: currentData.value.map(item => {
        const timeStr = item.dataTime
        const hour = timeStr.slice(-2)
        return `${hour}:00`
      }),
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: "value" as const,
      name: "电流值(A)",
      nameLocation: "middle" as const,
      nameGap: 40,
      max: maxValue.value, // 动态最大值
      min: 0
    },
    series: [
      {
        name: "A相电流",
        type: "line" as const,
        data: currentData.value.map(item => item.valueA),
        lineStyle: { color: "#f39c12" },
        itemStyle: { color: "#f39c12" },
        smooth: true
      },
      {
        name: "B相电流",
        type: "line" as const,
        data: currentData.value.map(item => item.valueB),
        lineStyle: { color: "#27ae60" },
        itemStyle: { color: "#27ae60" },
        smooth: true
      },
      {
        name: "C相电流",
        type: "line" as const,
        data: currentData.value.map(item => item.valueC),
        lineStyle: { color: "#e74c3c" },
        itemStyle: { color: "#e74c3c" },
        smooth: true
      }
    ]
  }
})
// 事件
const commEvent = {
  // 获取菜单信息
  getMenus: async () => {
    const { data } = await organTree()
    menus.value = commEvent.formatMenu(data)
    if (data && data.length > 0) {
      const _id: number = data[0].id
      menuId.value = _id
      openId.value = [_id]
    }
    commEvent.getDevice(true)
  },
  // 格式化菜单树
  formatMenu: (data: SystemApi.OrganTree[], pids?: number[]): any[] => {
    if (!data || data.length <= 0) return []
    return data.map(item => {
      let pidArr: number[] = []
      if (pids) {
        pidArr = [...pids, item.pid || 0]
      }
      return {
        id: item.id,
        text: item.organName,
        level: item.level,
        pid: item.pid,
        pidArr,
        children: commEvent.formatMenu(item.childrenTree || [], pidArr)
      }
    })
  },
  // 菜单点击
  menuClick: (item: any) => {
    if (item.level === 1) {
      menuValue.value.factoryId = item.id
      menuValue.value.lineId = undefined
    } else if (item.level === 2) {
      menuValue.value.factoryId = item.pid
      menuValue.value.lineId = item.id
    } else {
      menuValue.value.factoryId = undefined
      menuValue.value.lineId = undefined
    }
    commEvent.getDevice(true)
  },
  // 重置
  onReset: () => {
    commEvent.getDevice()
  },
  // 获取设备信息
  getDevice: async (load?: boolean) => {
    const params = {
      ...menuValue.value
    }
    const { data } = await deviceList(params)
    devices.value = data
    searchValue.value.deviceId = data && data.length ? data[0].id : undefined
    if (load) {
      commEvent.getRealTimeData()
    }
  },
  // 获取实时数据
  getRealTimeData: async () => {
    if (!searchValue.value.deviceId) {
      currentData.value = []
      return
    }
    // 获取三相电流数据
    await commEvent.getCurrentData()
  },

  // 获取三相电流数据
  getCurrentData: async () => {
    if (!searchValue.value.deviceId) {
      currentData.value = []
      return
    }
    // 调用正确的三相电流API
    const { data } = await RealTimeStatQuery({ deviceId: searchValue.value.deviceId })
    currentData.value = data
  }
}
onMounted(() => {
  commEvent.getMenus()
})
</script>

<style lang="scss" scoped>
.realtimemonito-box {
  display: flex;
  width: 100%;
  height: calc(100vh - 100px);
  .card__title {
    position: relative;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    padding-left: 8px;
    font-size: 16px;
    font-weight: bold;
    &::before {
      position: absolute;
      left: 0;
      width: 3px;
      height: 75%;
      content: "";
      background-color: var(--el-color-primary);
      border-radius: 16px;
    }
  }
  .content__left {
    width: 200px;
    :deep(.el-card__body) {
      padding: 0;
      height: 100%;
    }
    height: 100%;
    overflow-y: auto;
    padding-right: 4px; /* 为滚动条留空间 */
    scroll-behavior: smooth;
    /* 滚动条宽度 */
    &::-webkit-scrollbar {
      width: 3px;
    }

    /* 滚动条轨道 */
    &::-webkit-scrollbar-track {
      background: #f5f7fa;
      border-radius: 3px;
      margin: 2px 0; /* 上下留间距 */
    }
  }
  .content__right {
    box-sizing: border-box;
    flex: 1;
    width: 100%;
    min-width: 0;
    padding: 0 10px;
    overflow-y: auto;
    .header-search__item {
      display: flex;
      align-items: center;
      width: 100%;
      .item__label {
        font-size: 14px;
      }
      .item__value {
        flex: 1;
      }
    }
    .list__card {
      width: 100%;
      margin-bottom: 20px;
      .item__title {
        font-size: 14px;
      }
      .item__num {
        margin-top: 5px;
        font-size: 28px;
        font-weight: bold;
      }
      .item__time {
        margin-top: 5px;
        font-size: 12px;
      }
    }

    .chart-container {
      padding: 20px 0;
      flex: 1;
      :deep(.echarts-container) {
        border-radius: 8px;
      }
    }
  }
}
</style>
